const db = require('../db')
const bcryptjs = require('bcryptjs')
const schema = require('../schema')
const {validationUtil, procWhere, procOrder} = require('./util')
const auth = require('../auth')
const captcha = require('../util/captcha')
const {redisCli} = require('../redis')
const Lock = require('../util/lock')

// 添加 role-auth   
exports.add = (req, res) => {
    let obj = req.body
    // 1.检测表单数据是否合法；
    validationUtil(schema.roleAuthSchema.roleAuthAdd, obj) // 验证失败抛异常，被全局错误处理器处理 
    
    db.RoleAuth.create({
        ...obj
    }).then(result => {
        console.log('insert result', JSON.stringify(result)) 
        // 判断影响行数是否为1
        if(!result) return res.cc('角色权限关联失败')
        // 注册成功 
        res.cc('角色权限关联成功', 0)
    }).catch(err => {
        console.log(err) 
        res.cc(err)
    })
}

// 查询列表 
exports.list = (req, res) => {
    let params = req.body
    // 1.检测表单数据是否合法；
    validationUtil(schema.roleAuthSchema.roleAuthList, params) // 验证失败抛异常，被全局错误处理器处理 
    
    // 2.查询 
    let where = procWhere(params.where, db.RoleAuthAttributes) 
    let options = {
            where
        }
    db.RoleAuth.findAll(options).then(results => {
        // console.log('results: ', results)
        // 查询total 
        res.json({
            status: 0,
            message: 'success',
            data: results
        })
    }).catch(err => {
        console.log(err) 
        res.cc(err)
    })
}

// 删除   
exports.delete = (req, res) => {
    let params = req.body
    console.log('params', params)
    // 1.检测表单数据是否合法；
    validationUtil(schema.roleAuthSchema.roleAuthDelete, params) // 验证失败抛异常，被全局错误处理器处理 
    if(!params.ids.length) return res.cc('参数ids为空,无需删除', 0)
    
    // 2.查询 
    db.RoleAuth.destroy({
        where: {
            id: params.ids
        }
    }).then(results => {
        console.log('results', results)
        res.json({
            status: 0,
            message: 'success',
            data: results
        })
    }).catch(err => {
        console.log(err) 
        res.cc(err)
    })
}

